package com.bosch.in.rtp1.ept.manager.impl;

import java.sql.SQLException;

import com.bosch.in.rtp1.ept.dao.DurationColorConDao;
import com.bosch.in.rtp1.ept.manager.DurationColorConManager;
import com.bosch.in.rtp1.ept.model.dto.DurationColorCon;
import com.bosch.in.rtp1.ept.util.DaoFactory;
import com.bosch.in.rtp1.ept.util.ehcache.EhcacheFactory;

/**
 * Concrete implementation of SkpFshRcpManager which provides service to manipulate 
 * Duration color condition data, delegate data source retrieval and transaction management to 
 * DBConnectionManager attribute.  
 * @author LIV1HC
 *
 */

public class DurationColorConManagerImpl implements DurationColorConManager{
	
	
	private static final String COLOR_KEY = "color key";
	
	/**
	 * used to manage connection
	 */
	private DBConnectionManager dbManager;
	
	/**
	 * dao object
	 */
	private DurationColorConDao durationColorConDao;
	
	public DurationColorConManagerImpl(){
		
	}

	/**
	 * lazy initialize connection when we really need to interact with database and in case 
	 * data can't be found in caching system.
	 * @throws SQLException
	 */
	private void init() throws SQLException {
		if (dbManager == null) {
			dbManager = new DBConnectionManager();
			durationColorConDao = DaoFactory.getInstance().getDurColorDao(dbManager.getConnection());
		}
	}

	@Override
	public DurationColorCon getDuratonColCon() throws SQLException {
		try
		{
			DurationColorCon durColCon = EhcacheFactory.getDurColcacheWrapper().get(COLOR_KEY);
			if (durColCon == null) {
				// lazy init connection
				init();
				durColCon = durationColorConDao.getDuratonColCon();
				EhcacheFactory.getDurColcacheWrapper().put(COLOR_KEY, durColCon);
			}
			
			return durColCon;
		}
		finally
		{
			if (dbManager != null) {
				dbManager.close();
			}
		}
	}

	@Override
	public boolean updateColorCol(DurationColorCon durColCon) throws SQLException  {
		try
		{
			// lazy init connection
			init();
			// invalid current caching item
			EhcacheFactory.getDurColcacheWrapper().invalidate(COLOR_KEY);
			return durationColorConDao.updateColorCol(durColCon);
		}
		finally
		{
			dbManager.commit();
			dbManager.close();
		}
	}


	
}
